
from rest_framework import serializers

from goods.models import SKU
from goods.search_indexes import SKUIndex

from orders.models import OrderGoods

from drf_haystack.serializers import HaystackSerializer
from django_redis import get_redis_connection


class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = '__all__'


class SKUSearchSerializer(HaystackSerializer):
    # 嵌套序列化
    object = SKUSerializer(read_only=True)

    class Meta:
        index_classes = [SKUIndex]
        fields = ('text', 'object')


class SKUHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=0)

    def validate(self, attrs):
        # 校验sku_id所对应的商品是否存在
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        return attrs

    def create(self, validated_data):
        # 商品存在则保存在redis中
        # 获取用户对象
        user = self.context['request'].user
        # 1、建立redis连接
        conn = get_redis_connection('history')
        # 2、判断sku_id是否存储过  lrem             1    [1,2,3,4,5]
        conn.lrem('history_%s' % user.id, 0, validated_data['sku_id'])
        # 3、存储sku_id Lpush
        conn.lpush('history_%s' % user.id, validated_data['sku_id'])
        # 4、控制存储数量 ltrim.
        conn.ltrim('history_%s' % user.id, 0, 4)

        return validated_data


class SKUCommentsSerializer(serializers.Serializer):
    username= serializers.CharField(min_length=0)
    comment = serializers.CharField(min_length=5)
    score = serializers.IntegerField(min_value=0,max_value=5)



"""
{

    {
        'text':'Apple MacBook Pro 13.3英寸笔记本 银色  1 【全新2017款】MacBook Pro,一身才华，一触，即发 了解【黑五返场特惠】 更多产品请点击【美多官方Apple旗舰店】'
        'object':{
            'name':'apple 10'
            'ID：12
            'price':
        
        }
    
    }
}
"""
